package com.wwdx.service.impl;

import com.google.common.collect.Maps;
import com.wwdx.model.WwdxCardModel;
import com.wwdx.service.WwdxCardServiceI;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author liguoliang
 * @date 2018/9/14 13:05
 */
@Service
public class WwdxCardServiceImpl extends BaseServiceImpl<WwdxCardModel> implements WwdxCardServiceI {

    @Override
    public Long selectModelCount(WwdxCardModel model) {
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(4);
        String hql = "select count(1) from WwdxCardModel\t"+getParams(model,params);
        return count(hql,params);
    }

    private String getParams(WwdxCardModel model, Map<String, Object> params){
        StringBuilder sb = new StringBuilder("where 1=1\n");
        Integer type = model.getType();
        if (type != null){
            sb.append("and type=:type\n");
            params.put("type",type);
        }
        String date = model.getDate();
        String dateEnd = model.getDateEnd();
        if (StringUtils.isNotBlank(date) && StringUtils.isNotBlank(dateEnd)){
            date = new LocalDate(date).toString();
            dateEnd = new LocalDate(dateEnd).toString();
            sb.append("and date BETWEEN :date AND :date_end\n");
            params.put("date",date);
            params.put("date_end",dateEnd);
        }
        return sb.toString();
    }

    @Override
    public List<WwdxCardModel> selectModelList(WwdxCardModel model, Integer page, Integer rows) {
        Map<String, Object> params = Maps.newHashMapWithExpectedSize(4);
        String filed = model.getSort();
        String sort = "date";
        if (StringUtils.isNotBlank(filed)){
            sort = filed;
        }
        String hql = "from WwdxCardModel\t"+this.getParams(model, params)+"\torder by "+sort+" "+model.getSortOrder()+"";
        return find(hql, params, page, rows);
    }
}